import { gql } from 'graphql-request';
import graphQLClient from '../index';

async function getArticleById(id,selection={
  user:['id','title','url'],user:[],classify:[]
}){

  const query = gql`
  query getArticle($id:Int!){
    article(id:$id){
      ${selection.article.join()}
      ${selection.user&&selection.user.length>0?`
      _user{
        ${selection.user.join()}
      }
      `:''}
      ${selection.classify&&selection.classify.length>0?`
      _classify{
        ${selection.classify.join()}
      }
      `:''}
    }
  }`

  return await graphQLClient.request(query,{
    id
  })
}

async function getArticles(selection={
  article:['id','title','url'],user:[],classify:[]
},page={
  current:0,
  size:5
},where={},sort={}){

  const query = gql`
  query getArticles($page:PageInput,$sort:ArticleSortInput,$where:ArticleWhereInput){
    articles(page:$page,sort:$sort,where:$where){
      page{
        current,size,total
      }
      articles{
        ${selection.article.join()}
        ${selection.user&&selection.user.length>0?`
        _user{
          ${selection.user.join()}
        }
        `:''}
        ${selection.classify&&selection.classify.length>0?`
        _classify{
          ${selection.classify.join()}
        }
        `:''}
      }
    }
  }`

  return await graphQLClient.request(query,{
    page,sort,where
  })
}

async function addArticle(article){
  const mutation = gql`
  mutation addArticle($article:ArticleInput!){
    addArticle(article:$article){
      id,title
    }
  }`

  return await graphQLClient.request(mutation,{
    article
  })
}

async function modifyArticleById(id,article){
  const mutation = gql`
  mutation modifyArticle($id:Int!,$article:ArticleInput!){
    modifyArticle(id:$id,article:$article){
      id,name
    }
  }`

  return await graphQLClient.request(mutation,{
    id,article
  })
}

async function removeArticle(id){
  const mutation = gql`
  mutation removeArticle($id:Int!){
    removeArticle(id:$id){
      id,name
    }
  }`

  return await graphQLClient.request(mutation,{
    id
  })
}


export {
  getArticleById,getArticles,modifyArticleById,removeArticle
}